package com.katze.boot.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.katze.boot.file.dao.FileMapper;
import com.katze.boot.file.entity.FileEntity;
import com.katze.boot.file.service.FileService;
import com.katze.common.Pagination;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;


/**
* 说  明： 文件服务类
* 作  者：admin
* 日  期：2023-12-07
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class FileServiceImpl extends ServiceImpl<FileMapper, FileEntity> implements FileService {
    private static final Logger log = LoggerFactory.getLogger(FileServiceImpl.class);

    @Override
    public Object findFiles(Pagination pagination, FileEntity file) {
        try {
            QueryWrapper<FileEntity> wrapper = Wrappers.query(FileEntity.class)
                    .like(StringUtils.isNotBlank(file.getName()), "f.name", file.getName())
                    .eq(StringUtils.isNotBlank(file.getFileDatabaseId()), "f.file_database_id", file.getFileDatabaseId())
                    .eq(StringUtils.isNotBlank(file.getFileDatabaseExtendId()), "f.file_database_extend_id", file.getFileDatabaseExtendId())
                    .eq(Objects.nonNull(file.getOwner()), "f.owner", file.getOwner())
                    .orderByDesc("f.update_time", "f.create_time");
            if (pagination.isEnabled()) {
                return this.page(pagination.toPage(), wrapper);
            } else {
                return this.list(wrapper);
            }
        } catch (Exception e) {
            log.error("获取文件记录失败", e);
            return null;
        }
    }

    @Override
    @Transactional
    public File create(FileEntity file, Consumer<File> action) {
        if (save(file)) {
            File target = new File(file.getPath(), file.getUniqueName());
            action.accept(target);
            return target;
        } else {
            throw new IllegalStateException("存储文件保存失败");
        }
    }

    @Override
    public void delete(String... id) {
        List<FileEntity> files = this.baseMapper.selectBatchIds(Arrays.asList(id));
        files.forEach(item -> {
            File file = new File(item.getPath(), item.getUniqueName());
            if (!file.exists() || (file.exists() && file.delete())) {
                this.baseMapper.deleteById(item.getId());
            }
        });
    }

}
